package com.dxl.common.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;


/**
 * 文件工具类
 * @author 邓小林
 */
public final class FileUtils {
	public static List<String> readFile(File fileToRead, String encoding) throws Exception {
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(new BufferedInputStream(new FileInputStream(fileToRead), 512), Utils.isBlank(encoding) ? "utf-8" : encoding));
			List<String> lines = new ArrayList<String>();
			String line;
			while (!Utils.isNull(line = br.readLine())) {
				lines.add(line);
			}
			return lines;
		} finally {
			Utils.closeQuietly(br);
		}
	}
	
	public static String fileSuffix(String fileName) {
		if (Utils.isNotBlank(fileName) && fileName.contains(".")) {
			return fileName.substring(fileName.lastIndexOf(".") + 1);
		}
		return "";
	}
	
	public static File ensureFile(String filePath) throws IOException {
		if (Utils.isNotBlank(filePath)) {
			File file = new File(filePath);
			if (Utils.isNotNull(file.getParentFile())) {
				ensureDir(file.getParent());
			}
			if (!file.exists()) {
				file.createNewFile();
			}
			return file;
		}
		return null;
	}
	
	public static void ensureDir(String dirPath) {
		if (Utils.isNotBlank(dirPath)) {
			File dir = new File(dirPath);
			if (!dir.exists()) {
				dir.mkdirs();
			}
		}
	}
}
